/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iwords.android;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.http.client.methods.HttpPost;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.widget.Toast;

import com.iwords.android.WordLibsManager.WordLib;

/**
 * 当用户选择词库后，如果是个新词库，则显示词库下载到本地的过程，避免出现超时现象
 */
public class DownloadWordsLib extends Activity implements Callback{
    
    private LogTextBox mText;
    private Handler appHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.data_migration);
        
        mText = (LogTextBox) findViewById(R.id.text);
        appHandler = new Handler(this);
        mText.append("开始下载所选词汇到本地...\n");
        IWordsApp iWordsApp = (IWordsApp) getApplicationContext();
        final long userid = iWordsApp.getUser().getUserid();
        final long currentlib = this.getIntent().getLongExtra("currentWordLibId", -1);
		new Thread(new Runnable() {  
	        public void run() { 
	        	download(userid, currentlib);
	        }
		}).start();

    }
    
	@Override
	public boolean handleMessage(Message msg) {
    	mText.append(msg.obj.toString());
    	return true;
    }
	
	private void log(String msg){
    	Message message = new Message();
    	message.obj = msg;
    	appHandler.sendMessage(message);

	}
    
    private void download(long userid, long libid){
        if(userid == -1){
        	log("参数不合法...\n");
        }
        
		DBHelper dbHelper = new DBHelper(this);
		try{
        	WordLib lib = getLib(libid);
        	if(lib==null){
        		log("参数错误，不能获取课本【libid="+libid+"】...\n");
        		return;
        	}
        	log("开始下载"+lib.libName+"...\n");
        	DBHelper.UserLibs userLib = new DBHelper.UserLibs();
        	userLib.iscurrent = true;
        	userLib.libid = libid;
        	userLib.userid = userid;
        	userLib.pid = lib.pId;
        	userLib.libname = lib.libName;
    		//System.out.println("ChangeWordLib.userSelectedWordLib() to be inserted lib.libName="+lib.libName);
    		dbHelper.insert(userLib);
    		downloadWords(userid, libid, dbHelper);
    		log("下载完成，启动背单词...\n");
			Intent intent = new Intent(this, ProgressingActivity.class);
			intent.putExtra("currentLibId", userLib.libid);
			this.startActivity(intent);
			this.finish();
		}finally{
			dbHelper.cleanup();
		}
    }
	private WordLib getLib(long libid){
		String href = this.getResources().getString(R.string.book_detail);
		href += libid;
		HttpPost request = new HttpPost(href);
		//System.out.println("DataMigration.getLib()! href=" + href);
		try {
			JSONObject jSONObject = ServerAccessor.access(this, request);
			boolean success = jSONObject.getBoolean("isSuccess");
			if (!success) {
				this.displayMessage(CodeUtils.decode(jSONObject.getString("message")));
				return null;
			}
			JSONObject libJSON = jSONObject.getJSONObject("defaultValue");
			WordLib wordLib = new WordLib(
					CodeUtils.decode(libJSON.getString("libname")),
					libJSON.getLong("libid"), 
					libJSON.getLong("pid"), 
					Boolean.FALSE, 
					libJSON.getInt("sysliblevel"), 
					(libJSON.getInt("sysliblevel")==4));
			return wordLib;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
    }
	
	private int downloadWords(long userid, long libid, DBHelper dbHelper){
		String href = this.getResources().getString(R.string.sys_word_list);
		href = href + libid;
		HttpPost request = new HttpPost(href);
		//System.out.println("---DataMigration.downloadWords()! href = "+ href);
		int knownCount = 0;
		try {
			JSONObject jSONObject = ServerAccessor.access(this, request);
			boolean success = jSONObject.getBoolean("isSuccess");
			if (!success) {
				this.displayMessage(CodeUtils.decode(jSONObject.getString("message")));
				return knownCount;
			}
			JSONArray wordsList = JSONUtils.getArray(jSONObject.getJSONObject("defaultValue"));
			//System.out.println("---WordsQueueManager.loadCurrentQueue()! wordsList = " + wordsList.length());
			log("共有词汇"+wordsList.length()+"个...\n");
			Set<String> knowns = dbHelper.getUserKnowns(userid);
			for (int i = 0; i < wordsList.length(); i++) {//"wordid","syslibid","meaning","phonetics","spelling","createtime","updatetime"
				JSONObject jsonObject = wordsList.getJSONObject(i);
				DBHelper.LearningStatus status = new DBHelper.LearningStatus();
				status.userid = userid;
				status.wordid = jsonObject.optLong("wordid");
				status.libid = jsonObject.optLong("syslibid");
				status.spelling = CodeUtils.decode(jsonObject.optString("spelling"));
				status.phonetics = CodeUtils.decode(jsonObject.optString("phonetics"));
				status.meaning = CodeUtils.decode(jsonObject.optString("meaning"));
				status.createTime = new Date(System.currentTimeMillis());
				status.updateTime = new Date(System.currentTimeMillis());
				//根据用户的掌握情况，过滤掉已经记住的单词
				status.familiarity = 0;//初始化的时候是0
				if(knowns.contains(status.spelling.trim())){
					status.familiarity = 7;
					knownCount++;
				}
				dbHelper.insert(status);
				if(i>0 && i%100==0){
					log("已下载词汇"+i+"个...\n");
				}
			}
			log("共下载词汇"+wordsList.length()+"个...\n");
			log("其中"+knownCount+"个是已经记住的单词，无需再记");
		} catch (Exception e) {
			this.displayMessage(e.getMessage());
		}
		return knownCount;
	}
	
	private void displayMessage(String message) {
		//Looper.prepare();
		Toast t1 = Toast.makeText(this, message, Toast.LENGTH_LONG);
		t1.show();
	}

}
